<?php
/**
 * 抽奖
 */
class Lottery extends BZ_Controller
{
    private $headTitle = '';
    private $wximg = 'images/draw300x300.jpg';

    public function _init()
    {
        $this->load->helper('common');
        $this->load->model('user_model', 'user');
        $this->load->model('user_account_model', 'user_account');
        $this->load->model('activity_lottery_model', 'activity_lottery');
        $this->load->model('user_lottery_model', 'user_lottery');
        $this->load->model('lottery_prize_model', 'lottery_prize');
        $this->load->model('lottery_winner_model', 'lottery_winner');
        $this->load->model('prize_every_day_model', 'prize_every_day');
        $this->load->model('bind_user_model', 'bind_user');
        $this->load->model('getpwd_phone_model', 'getpwd_phone');
        $this->load->model('user_account_model', 'user_account');
        $this->load->model('lottery_reseller_model', 'lottery_reseller');
    }

    //微信授权
    public function index()
    {
        $activity = $this->lotteryIsExists();
        if ($activity == FALSE) {
            $this->redirect('home/lottery/lottery404/');
        }

        $username = $this->input->get('username');
        if ($username == 'fx7459') {  //建行过来的
            set_cookie('lottery_user', 'ccb', 7200);
        }
        $this->wxShare($username, $activity); //分享

        $activityPrize = $this->getPrizes($activity->lottery_id);
        if ($activityPrize == FALSE) {
            $this->redirect('home/lottery/lottery404');
        }

        set_cookie('lotteryunid', $activity->lottery_id, 36000);

        if (validateWeiXin()) { //如果通过微信 参加抽奖
            $openUser = json_decode(get_cookie('bzopen'));
            if (empty($openUser->openid)) {
                $openUser = $this->weChat($username);
            }
            if ( !empty($openUser->openid)) {
                $bindUser = $this->bind_user->findByOpenId($openUser->openid);
                if ($bindUser->num_rows() > 0) {
                    $error = $this->_login($bindUser->row()->uid);  //微信过来  直接登录
                    if ($error) {
                        $this->alertError($error);
                    }
                }
            }
        }
        $this->data['activityPrize'] = $activityPrize;
        $this->data['wximg'] = $this->wximg;
        $this->data['lottery'] = $activity;
        $this->load->view('home/lottery/index', $this->data);  //未绑定  需要填写手机号码  注册 然后绑定
    }

    /**
     * 分享  微信直接分享
     * 如果url参数没有username  且已登录的账号是分销商 就把url加上 username=name 的参数
     */
    private function wxShare($username, $activity)
    {
        if ($username && $username == $this->userName) {
            return TRUE;
        }

        //如果是现场颁奖
        if ($activity->on_line == 2) {
            $state = TRUE;
            $reseller = array($this->userName);
            if ($username) {
                array_push($reseller, $username);
            }
            if (empty($reseller)) {
                $this->redirect('home/lottery/lottery403');
            }
            $result = $this->lottery_reseller->findByName($activity->lottery_id, $reseller);
            if ($result->num_rows() == 0) {
                $this->redirect('home/lottery/lottery403');
            }
            foreach ($result->result() as $value) {
                if ($this->userName == $value->reseller_name) {
                    $state = FALSE;
                }
            }

            if ($state) {  //当前用户 没有现场颁奖权限
                return TRUE;
            }
        }
        if ($this->uid && ((int)$this->userType & UTID_SELLER) == UTID_SELLER) {
            $getData = $this->input->get();

            $getData['username'] = $this->userName;
            $url = site_url('home/lottery/index'). '?'. http_build_query($getData) ;
            $this->redirect($url);
        }
    }

    public function lottery404()
    {
        $this->load->view('home/lottery/lottery_404', $this->data);
    }

    public function lottery403()
    {
        $this->load->view('home/lottery/lottery_403', $this->data);
    }

    /**
     * 活动介绍
     */
    public function introduce()
    {
        $activity = $this->lotteryIsExists();
        if ($activity == FALSE) {
            $this->redirect('home/lottery/lottery404');
        }
        $details = empty($activity->page2) ? '' : json_decode($activity->page2);
        if ( empty($details->content)) {
            $this->redirect('home/lottery/lottery404');
        }
        $this->data['details'] = $details;
        $this->load->view('home/lottery/introduce', $this->data);
    }

    //用户参与抽奖接口
    public function participate()
    {
        if ($this->uid) {
            $this->redirect('home/lottery/draw');
        }
        $activity = $this->lotteryIsExists();
        if ($activity == FALSE) {
            $this->redirect('home/lottery/lottery404');
        }
        if (validateWeiXin()) {
            $openUser = json_decode(get_cookie('bzopen'));
            if (empty($openUser->openid)) {//如果微信  没有授权
                $this->redirect('home/lottery/index');
            }
            $bindUser = $this->bind_user->findByOpenId($openUser->openid);
            if ($bindUser->num_rows() > 0) {
                $this->redirect('home/lottery/draw');// 已绑定 可以直接参与抽奖
            }
        }
        $this->data['lottery'] = $activity;
        $this->data['wximg'] = $this->wximg;
        $this->load->view('home/lottery/participate', $this->data);
    }

    /**
     * 参与抽奖
     */
    public function participatePost()
    {
        $activity = $this->lotteryIsExists();
        if (empty($activity)) {
            $this->jsonMessage('活动异常');
        }

        $mobilePhone = $this->input->post('mobilePhone');
        if (empty($mobilePhone)) {
            $this->jsonMessage('请填写手机号码');
        }

        if ( ! valid_mobile($mobilePhone)) {
            $this->jsonMessage('手机号码为11位数字');
        }

        if (strlen($this->input->post('captcha')) != 6) {
            $this->jsonMessage('请填写正确的手机校验码');
        }

        $captcha = $this->getpwd_phone->validateCaptcha($mobilePhone, $this->input->post('captcha'));
        if ($captcha->num_rows() == 0) {
            $this->jsonMessage('短信效验码错误');
        }

        $code = rand(100000, 999999);
        $result = $this->user->validateMobilePhone($mobilePhone);
        $openUser = json_decode(get_cookie('bzopen'));

        if ($result->num_rows() == 0) { //手机未注册 将其注册为消费者
            $parentId = 16;

            $username = get_cookie('true_user');
            if ($username) {
                $userResult = $this->user->validateName($username);
                if ($userResult->num_rows() > 0) {
                    $userResult = $userResult->row();
                    if (((int)$userResult->user_type & UTID_SELLER) === UTID_SELLER) {
                        $parentId = $userResult->uid;
                    }
                }
            }

            $postData = array('user_name' => $mobilePhone, 'mobile_phone' => $mobilePhone, 'alias_name' => $mobilePhone);
            if ( !empty($openUser->nickname)) { //微信存在表情  无法存储到数据库
                $postData['alias_name'] = $openUser->nickname;
            }

            if (!empty($openUser->personal_photo)) {
                $postData['personal_photo'] = $openUser->personal_photo;
            }
            $this->db->trans_begin();
            $userId = $this->user->insertUser($postData, $parentId);
            $userAccountId = $this->user_account->insertUserAccount($userId);
            if ($this->db->trans_status() === FALSE || !$userId || !$userAccountId) {
                $this->db->trans_rollback();
                $this->alertJumpPre('用户参与抽奖失败');
            } else {
                $this->db->trans_commit();
                // $this->sendToSms($mobilePhone, '尊敬的用户：感谢您参与着想科技幸运大转盘活动，您已成功注册着想会员，您的着想账号为：'. $mobilePhone.'，初始密码：'. $code.'，请使用着想账号查看中奖情况，如有疑问请致电400-0571-648，更多产品请登录wap.zxkj918.com查看。', 2);
            }
        } else {    //注册过 就跟现有的用户绑定
            $userId = $result->row()->uid;
            // $this->sendToSms($mobilePhone, '敬的会员：您好！感谢您参与着想科技幸运大转盘活动，请使用您的着想账号登录查看中奖情况，如有疑问请致电400-0571-648，去wap.zxkj918.com着想科技逛逛。', 2);
        }

        //如果是微信
        if ( !empty($openUser->openid)) {
            $bindUser = $this->bind_user->findByOpenId($openUser->openid);
            if ( $bindUser->num_rows() == 0 ) {
                $isBind = $this->bind_user->insertBindUser(array('uid' => $userId, 'openid' =>$openUser->openid));
                if ( !$isBind) {
                    $this->jsonMessage('用户参与抽奖失败');
                }
            }
        }
        $error = $this->_login($userId);
        if ($error) {
            $this->jsonMessage($error);
        }
        $this->jsonMessage('', site_url('home/lottery/draw'));
    }

    /**
     * 微信授权
     */
    protected function weChat($username)
    {
        include_once(getcwd()."/application/libraries/wxpay/WxPayPubHelper/WxPayPubHelper.php");
        $jsapi = new JsApi_pub();
        if (!isset($_GET['code'])) {
            $return_url = urlencode(site_url('home/lottery/index').'?id='. $this->input->get('id').$username);
            $url = $jsapi->createOauthUrlForCode($return_url);
            header("Location:$url");
        }
        
        $jsapi->setCode($_GET['code']);
        $result = $jsapi->curl($jsapi->createOauthUrlForOpenid());
        $urlOne = "https://api.weixin.qq.com/sns/userinfo?access_token=".$result->access_token."&openid=".$result->openid."&lang=zh_CN";
        $userInfo = $jsapi->curl($urlOne);
        $openUser = array('openid' => $userInfo->openid, 'personal_photo' => $userInfo->headimgurl, 'nickname' => filterEmoji($userInfo->nickname));
        set_cookie('bzopen', json_encode($openUser), 7200);
        return (object)$openUser;
    }

    /**
     * 获取微信 信息
     * @param $url
     * @return array|mixed|object
     */
    private function getUrlInfo($url)
    {
        $ch  = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);   //返回原生的（Raw）输出
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //可以设置为验证站点
        $result = curl_exec($ch);
        curl_close($ch);//解析 得到openid,打开绑定页面 传openid
        $resource = json_decode($result);
        return $resource;
    }

    public function draw()
    {
        if (empty($this->uid)) {
            $this->redirect(site_url('login/login/index')); //去登陆
        }

        $activity = $this->lotteryIsExists();
        if ($activity == FALSE) {
            $this->redirect('home/lottery/lottery404');
        }

        $result = $this->getPrizes($activity->lottery_id);
        if ($result == FALSE) {
            $this->redirect('home/lottery/lottery404');
        }

        $userLottery = $this->user_lottery->findToday($this->uid, $activity->lottery_id);
        if ($userLottery->num_rows() == 0) {
            $entrance = array();
            if ($activity->lottery_sum > 0 && $activity->winning_num > 0) {
                for ($i=0; $i < $activity->winning_num; $i++) {
                    $entrance[] = mt_rand(1, $activity->lottery_sum); 
                }
            }
            $postData = array(
                'uid'          => $this->uid,
                'user_name'    => $this->userName,
                'lottery_id'   => $activity->lottery_id,
                'today_num'    => $activity->lottery_sum,
                'entrance'     => empty($entrance) ? '' : json_encode($entrance),
                'reseller_name'=> get_cookie('true_user')
            );
            $id = $this->user_lottery->insertUser($postData);
            $this->activity_lottery->setUserTotal($activity->lottery_id); //用户抽奖人数加1

            $activity->user_total += 1;
            $this->setLotteryCache($activity); //更新参与抽奖人数
            if ( !$id) {
                $this->alertJumpPre('用户参与抽奖失败');
            }
            $this->data['lotterySum'] = $activity->lottery_sum;
        } else {
            $this->data['lotterySum'] = $userLottery->row()->today_num;
        }

        $this->data['prizeArr'] = $this->drawFillDate($result);//转盘什么的奖品
        $this->data['prize'] = $result;
        $this->data['wximg'] = $this->wximg;
        $this->data['lottery'] = $activity;
        $this->load->view('home/lottery/drawLottery', $this->data);
    }

    /**
     * 抽奖奖品填充  暂时设为6个奖品
     * 一等奖颜颜色#FFD217,二等奖颜色#F3BA2F,三等奖颜色#FFE577,谢谢参与#FFFCD9
     */ 
    private function drawFillDate($prize)
    {
        $count = count($prize);
        $prizeArr = array();
        $num = $count <= 4 ? 6 : 8;
        $colors = $count <= 3 ? array('#f49e1b','#FFD217', '#F3BA2F') : array('#f49e1b','#FFD217', '#F3BA2F', '#FFE577');
        $half = $num /2; //总数的一半
        $surplus = $num - $count;
        $key = 0;
        for ($i = 0; $i <= $num ; $i++) {
            if ( ( ($i % 2) == 0 && $surplus > 0 ) || $key >= $count ) {
                $prizeArr[$i]['color'] = '#FFFCD9';
                $prizeArr[$i]['name'] = '谢谢参与';
                $prizeArr[$i]['id'] = 0;
                $surplus --;
            } else {
                $colorKey = $i >= $half ? $i - $half : $i;  //颜色的key
                $prizeArr[$i]['color'] = $colors[$colorKey];
                $prizeArr[$i]['id'] = $prize[$key]->prize_id;
                $key ++;
                $prizeArr[$i]['name'] = numberToZhUpper($key).'等奖';
            }
        }
        //由于画布从右的最下方开始  需要把最后3个转换顺序
        $prizeArr = array_chunk($prizeArr, $half);
        $prizeArr = array_merge($prizeArr[1], $prizeArr[0]);
        return $prizeArr;
    }

    /**
     * 活动是否存在
     * @return mixed
     */
    private function lotteryIsExists($state = false)
    {
        $id = $this->input->get('id');
        $lotteryId = ($id) ? $id : get_cookie('lotteryunid');
        if (empty($lotteryId)) {
            $lotteryId = 13; //着想活动的编号
        }

        $activity = $this->cache->memcached->get('activityLottery'.$lotteryId); //缓存该活动
        if (empty($activity) || $state) {
            $activity = $this->activity_lottery->findById($lotteryId);
            if ($activity->num_rows() == 0) {
                return FALSE;
            }
            $activity = $activity->row();
            $this->cache->memcached->save('activityLottery'.$lotteryId, $activity, 24 * 60 * 60);
        }
        $now = date('Y-m-d H:i:s');
        if ($activity->status == 1 && $activity->audit_state ==2 && $now > $activity->start_date && $now < $activity->end_date) {
            $titles = json_decode($activity->page1);
            $this->headTitle = (!empty($titles->title1) && !empty($titles->title2)) ? ($titles->title1. ','. $titles->title2) : '着想幸运大转盘,天天抽奖不打烊';
            return $activity;
        }

        return FALSE;
    }

    /**
     * 设置活动缓存
     */
    private function setLotteryCache($lottery)
    {
        $this->cache->memcached->save('activityLottery'.$lottery->lottery_id, $lottery, 24 * 60 * 60);
    }

    /**
     * 抽奖
     */
    public function ajaxGetDraw()
    {
        if (empty($this->uid)) {
            $this->errorLottery('参数错误，请从新进入');
        }
        $activity = $this->lotteryIsExists();
        if ($activity == FALSE) {
            $this->errorLottery('参数错误，请从新进入');
        }

        $drawNum = 0;
        //用户是否已参加抽奖活动
        $userLotteryResult = $this->user_lottery->findToday($this->uid, $activity->lottery_id);
        if ($userLotteryResult->num_rows() == 0) {
            $this->errorLottery('操作异常');
        }

        $userLottery = $userLotteryResult->row();
        $drawNum = $userLottery->today_num - 1;
        if ($userLottery->today_num <= 0) {
            $this->errorLottery(false);
        }
        if ($userLottery->weight >= $activity->winning_num) {//今天中奖已到达上限
            $this->closeLottery($activity->lottery_id, $drawNum);
        }

        if ( !empty($userLottery->entrance)) {
            $entrance = json_decode($userLottery->entrance, true);
            if ( !in_array($userLottery->today_num, $entrance)) {
                $this->closeLottery($activity->lottery_id, $drawNum);
            }
        }

        //查询参与抽奖的人数 总人数
        $totalPeopleNum = $this->user_lottery->total($activity->lottery_id);
        $totalPeopleNum = ($totalPeopleNum < 1000) ? 1000 : $totalPeopleNum;

        //查询某活动奖品信息
        $prizes_arr = $activityPrize = $this->getPrizes($activity->lottery_id);
        if ($activityPrize == FALSE) {
            $this->closeLottery($activity->lottery_id, $drawNum);
        }

        foreach ($prizes_arr as $key => $value) {
            if ($value->surplus_quantity <= 0) {
                unset($prizes_arr[$key]);
            } else {
                if ( !empty($value->winners_user)) {
                    $this->designatedWinningUser($value, $activity, $drawNum, $activityPrize);//指定中奖用户
                    $winnersUser = json_decode($prizeN->winners_user, true);
                    if ($value->surplus_quantity <= (count($winnersUser) - array_sum($winnersUser))) {
                        unset($prizes_arr[$key]);
                        continue;
                    }
                } else if ( empty($value->winners_user) && !empty($value->time_slot)) {
                    $this->designatedWinningTime($value, $activity, $drawNum, $activityPrize);
                }
                $prizes_arr[$key]->ratio = ($value->probability) ? $value->probability : (bcdiv($value->surplus_quantity,  $totalPeopleNum, 3) * 100);
            }
        }
        //没有剩余奖品了
        if (empty($prizes_arr)) {
            $this->closeLottery($activity->lottery_id, $drawNum);
        }

        //进行随机抽奖
        $draw_res = $this->drawMethod($prizes_arr);
        //该奖级今天是否还有剩余奖品
        if ($draw_res == FALSE) {
            $this->closeLottery($activity->lottery_id, $drawNum);
        }

        $this->jackpot($activity, $draw_res, $drawNum, $activityPrize);
    }

    /**
     * 中奖规则  -- 指定中奖用户
     */
    private function designatedWinningUser($prizeN, $lottery, $drawNum, $activityPrize)
    {
        $winnersUser = json_decode($prizeN->winners_user, true);
        if (array_key_exists($this->userName, $winnersUser) && $winnersUser[$this->userName] == 0) {  //指定中奖用户
            $winnersUser[$this->userName] = 1; //标记为已使用
            $prizeN->winners_user = json_encode($winnersUser);
            if ( !empty($prizeN->time_slot)) {//即指定了中奖用户，又指定了中奖时间
                $this->designatedWinningTime($prizeN, $lottery->lottery_id, $drawNum, $activityPrize);
            } else {
                $this->jackpot($lottery, $prizeN, $drawNum, $activityPrize);
            }
        }
    }

    /**
     * 中奖规则 ---  指定中奖时间
     */
    private function designatedWinningTime($prizeN, $lottery, $drawNum, $activityPrize)
    {
        $timeSlot = json_decode($prizeN->time_slot);
        foreach ($timeSlot as $key => $value) {
            if (date('Y-m-d H:i:s') >= $key && $value === 0) {
                $timeSlot->$key = 1; //标记为已使用
                $prizeN->time_slot = json_encode($timeSlot);
                //指定时间中奖
                $this->jackpot($lottery, $prizeN, $drawNum, $activityPrize);
            }
        }
    }

    //抽奖算法
    private function drawMethod($sorted_arr)
    {
        $rd = mt_rand(0,100);
        $st = 0;
        $ed = 0;
        $count = count($sorted_arr);
        foreach ($sorted_arr as $key => $value) {
            $ed += $value->ratio;
            if (($rd > $st) && ($rd <= $ed)) {
                return $value;
            }
        }
        return FALSE;
    }

    //抽完奖处理
    private function closeLottery($lottery_id, $drawNum)
    {
        //用户的今日剩余抽奖次数减一
        $res = $this->user_lottery->decrease_num($this->uid, $lottery_id);
        echo json_encode(array(
                'status' => true,
                'prize'  => 0,
                'drawNum'=> $drawNum
            ));
        exit;
    }

    /**
     * 活动参数错误
     */
    private function errorLottery($error)
    {
        echo json_encode(array(
                'status'   => false,
                'messages' => $error
            ));
        exit;
    }

    /**
     * json返回
     * @param bool $status
     * @param int $prizeId
     * @param string $text
     */
    private function jsonMessages($status, $prizeId, $text = '', $drawNum = 0, $img = '')
    {
        echo json_encode(array(
                'status' => $status,
                'prize'  => $prizeId,
                'text'   => $text,
                'drawNum'=> $drawNum,
                'img'    => $img
            ));
        exit;
    }

    /**
     * 获取该活动的奖品
     */
    private function getPrizes($lotteryId)
    {
        $activityPrize = $this->cache->memcached->get('activityPrize'.$lotteryId); //缓存该活动奖品
        if (empty($activityPrize)) {
            $activityPrize = $this->lottery_prize->findPrizes(array('lottery_id' => $lotteryId));
            if ($activityPrize->num_rows() == 0) {
                return FALSE;
            }
            $activityPrize = $activityPrize->result();
            $expires = strtotime(date('Y-m-d 23:59:59')) - time();
            $this->cache->memcached->save('activityPrize'. $lotteryId, $activityPrize, $expires); //缓存今天
        }
        return $activityPrize;
    }

    /**
     * 中奖了
     */
    private function jackpot($lottery, $drawRes, $drawNum, $prizesArr)
    {
        $this->db->trans_start();
        //将中奖用户信息插入中奖表
        $drawRes->uid = $this->uid;
        $drawRes->user_name = $this->userName;
        $drawRes->reseller_name = get_cookie('true_user');
        $this->activity_lottery->setWinnersTotal($lottery->lottery_id); //中奖总数添加1
        $this->lottery_winner->addUser($drawRes);
        //该奖品今日剩余奖品数量减一
        $this->prize_every_day->decreaseTodayNum($drawRes);
        //该用户当前活动权重增一
        $this->user_lottery->increaseWeight($this->uid, $lottery->lottery_id);
        $this->db->trans_complete();

        if ($this->db->trans_status() === TRUE) {
            foreach ($prizesArr as $key => $value) {
                if ($value->prize_id == $drawRes->prize_id) {
                    $prizesArr[$key] = $drawRes;
                    $prizesArr[$key]->surplus_quantity -= 1;
                    break;
                }
            }
            $expires = strtotime(date('Y-m-d 23:59:59')) - time();
            $this->cache->memcached->save('activityPrize'. $lottery->lottery_id, $prizesArr, $expires); //缓存今天

            $lottery->winners_total += 1;
            $this->setLotteryCache($lottery); //更新中奖数量
            $img = $this->config->show_image_thumb_url('lotteryPrize', $drawRes->image);
            $this->jsonMessages(true, $drawRes->prize_id, $drawRes->prize_name, $drawNum, $img);
        } else {
            $this->errorLottery('操作异常，数据更新失败');
        }
    }

    /**
     * 中奖名单
     */
    public function ajaxWinningList()
    {
        $activity = $this->lotteryIsExists();
        if ($activity == FALSE) {
            echo json_encode(array('html' => $this->load->view('home/lottery/winningList')));exit;
        }
        $data['winningList'] = $this->lottery_winner->findWinningList($activity->lottery_id);
        echo json_encode(
                array(
                    'html' => $this->load->view('home/lottery/winningList', $data, true)
                )
            );
        exit;
    }

    /**
     * 登录
     */
    private function _login($uid)
    {
        if (empty($this->uid)) {
            $result = $this->user->findById($uid);
            if ($result->num_rows() <=0) {
                return '用户不存在';
            }
            $user = $result->row();
            if (intval($user->user_type)&UTID_PROVIDER || intval($user->user_type)&UTID_TELLER) {
                return '供应商或检票帐号不可以登录哦';
            }

            if ($user->flag == 2) {
                return '此帐号已被冻结，请与管理员联系';
            }
            $this->user->visitCount($user->uid); //统计用户登录次数。
            $userType = $this->usertype($user->user_type);
            $session = array(
                'ACT_UID'        => $user->uid,
                'ACT_UTID'       => $user->user_type,
                'ACT_TYPENAME'   => urlencode($userType['type_zh']),
                'ACT_TYPE'       => $userType['type_en'],
                'ACT_EXTRA'      => $user->extra,
                'ALIAS_NAME'     => urlencode($user->alias_name),
                'OWNER_ID'       => $user->uid,
                'OWNER_NAME'     => $user->user_name,
                'PARENT_ID'      => $user->parent_id,
                'PERSONAL_PHOTO' => urlencode($user->personal_photo),
            );
            set_cookie('frontUser', serialize($session), 43250);
        }
        return FALSE;
    }
}